package com.my.config;

import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;

import java.io.InputStream;

/**
 * @author WangLuoXin
 * &#064;Date 2024/9/18  13:43
 * 配置文件解析
 **/
public class Flag {

    /**
     * 默认加载resource目录下 global.yaml 文件
     *
     * @return yaml 配置文件实体
     */
    public static GlobalConfig parse() {
//        Yaml yaml = new Yaml();
        Yaml yaml = buildYamlInstance(GlobalConfig.class);
        InputStream globalInput;
        //适配 spring boot 临时
        InputStream resourceAsStream = Flag.class.getClassLoader().getResourceAsStream("application.yaml");
        if (null == resourceAsStream) {
            globalInput = Flag.class.getClassLoader().getResourceAsStream("global.yaml");
        } else {
            globalInput = resourceAsStream;
        }

        if (globalInput != null) {
            return yaml.load(globalInput);
        } else {
            return new GlobalConfig();
        }
    }

    static String camelize(String input) {
        for (int i = 0; i < input.length(); i++) {
            if (input.substring(i, i + 1).equals("-")) {
                input.replace("-", "");
                input = input.substring(0, i) + input.substring(i + 1, i + 2).toUpperCase() + input.substring(i + 2);
            }
            if (input.substring(i, i + 1).equals(" ")) {
                input.replace(" ", "");
                input = input.substring(0, i) + input.substring(i + 1, i + 2).toUpperCase() + input.substring(i + 2);
            }
        }
        return input;
    }

    public static Yaml buildYamlInstance(Class<? extends Object> theRoot) {
        Constructor c = new Constructor(theRoot);
        c.setPropertyUtils(new PropertyUtils() {
            @Override
            public Property getProperty(Class<? extends Object> type, String name) {
                if (name.indexOf('-') > -1) {
                    name = camelize(name);
                }
                setSkipMissingProperties(true);
                return super.getProperty(type, name);
            }
        });
        return new Yaml(c);
    }
}
